package com.hefan.oms.dao;

import com.cat.tiger.util.DateUtils;
import com.hefan.common.exception.DataIllegalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Repository
public  class RechargeCodeKindItemDao {

    Logger logger = LoggerFactory.getLogger(RechargeCodeKindItemDao.class);

    @Resource
    JdbcTemplate jdbcTemplate;
    /**
     * 根据兑换码，获取对应有效的信息
     * @param code
     * @return
     */
    public Map findValidRechargeCode( String code)
    {
        Map resultMap = new HashMap();
        StringBuilder sb =  new StringBuilder(300);
        sb.append(" SELECT a.id,a.code,b.kind_name AS kindName,c.is_only as isOnly,c.id as rcId FROM recharge_code_kind_item a  " );
        sb.append(" JOIN recharge_code_kind b ON a.rck_id = b.id ");
        sb.append(" JOIN recharge_code c ON b.rc_id=c.id ");
        sb.append(" WHERE  a.code=? and a.status=1 AND a.flag=0 AND c.flag=0 ");
        sb.append(" AND c.start_time <=? AND c.end_time>= ? limit 1 ");
        try {
            resultMap = jdbcTemplate.queryForMap(sb.toString(),
                    new Object[]{code, new Date(), DateUtils.date2Str(new Date(),"yyyy-MM-dd")});
        }catch (EmptyResultDataAccessException e) {
            logger.error("查询结果为空 {}"+e.getMessage());
            return null;
        }

        return  resultMap;
    }

    /**
     * 检查唯一新批次是否已被用户使用
     * @param rcId
     * @param userId
     * @return
     */
    public int checkRechangeCodeIsOnly(int rcId, String userId) {
        String sql = "select count(1) as useNum from recharge_code_kind_item where rc_id=? and used_user_id=?";
        Integer useNum = this.jdbcTemplate.queryForObject(sql, new Object[]{rcId,userId},Integer.class);
        if (useNum == null) return  0;
        return useNum.intValue();
    }
    
    /**
     * 将充值设置为已使用
     * @param id 充值码主键
     * @param paySource 兑换渠道 1：PC端 2：IOS端 3：安卓端
     * @param userId 使用充值码的userId
     */
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int updateRechargeCodeIsUsed(int id, Integer paySource, String userId){
      String sql = "update recharge_code_kind_item set status=2,source=?,used_user_id=? where id=? and status=1 and flag=0";
      int result = jdbcTemplate.update(sql, paySource == null ? 0 : paySource,userId, id);
        if (result <= 0) {
            throw new DataIllegalException(String.format("更新充值码状态%s异常", id));
        }
        return result;
    }
    
}